// pages/unkeep/keep.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    fileList: [],
    maxCount: 6,
    isSubmitting: false,
    employeeList:[
      { id: 0, name: "弱电员工" },
      { id: 1, name: "水电员工" }
    ],
    selectedIndex: 0
  },
  onEmployeeSelect(e) {
    const index = e.detail.value; // 用户选择的索引
    const selectedEmployee = this.data.employeeList[index];
    this.setData({ selectedIndex: index });
    console.log("选中ID:", selectedEmployee.id, "名称:", selectedEmployee.name);
  },
  // 内容输入事件
  onContentInput(e) {
    this.setData({ content: e.detail.value });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  handleSubmit : async function(param){
    
    if (this.data.isSubmitting) return;
     // 校验逻辑
     if (!this.data.content.trim() && this.data.fileList.length === 0) {
      return wx.showToast({ title: '请填写内容或上传图片', icon: 'none' });
    }
    this.setData({ isSubmitting: true });
    try {
      // 改造点1：上传到自建服务器
      const uploadTasks = this.data.fileList.map(file => 
        this.uploadToOwnServer(file) // 自定义上传方法
      );
      
      const imageIds = await Promise.all(uploadTasks);
      console.log(imageIds);
      // 改造点2：提交表单数据到自建接口
      const selectedEmployee = this.data.employeeList[this.data.selectedIndex];
      console.log("选中ID:", selectedEmployee.id, "名称:", selectedEmployee.name);
      await this.submitFormData({
        content: this.data.content,
        imgIds: imageIds,
        type: selectedEmployee.id
      });
  
      wx.showToast({ title: '提交成功' });
      setTimeout(() => wx.navigateBack(), 1500);
    } catch (error) {
      console.error('提交失败:', error);
      wx.showToast({ title: error.message || '提交失败，请重试', icon: 'none' });
    } finally {
      this.setData({ isSubmitting: false });
    }

  },
  uploadToOwnServer(filePath){
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://ylapp.zhongqueproperty.cn/manager/app/upload/file', // 服务器接口地址
        filePath,
        name: 'file',
        method:'POST',
        header:{token:wx.getStorageSync('user_token')},
        success: (res) => {
         console.log(JSON.parse(res.data));
         const data = JSON.parse(res.data)
          if (data.code === 0) {
            resolve(data.data.data.id); 
          } else {
            reject(new Error(data.msg));
          }
        },
        fail: (err) => {
          reject(new Error('网络异常，请检查连接'));
        }
      });
    });
  },

  async submitFormData(formData) {
    
    wx.getStorageSync('token');
    wx.request({
      url: 'https://ylapp.zhongqueproperty.cn/manager/app/submit/order',
      method:"POST",
      header:{token:wx.getStorageSync('user_token')},
      data: JSON.stringify(formData),
      success: function(res) {
        if (res.data.code === 0) {
          resolve();
        } else {
          reject(new Error(res.data.msg));
        }
      }
    })
  },

   // 选择图片
   chooseImage() {
    wx.chooseMedia({
      count: this.data.maxCount - this.data.fileList.length,
      mediaType: ['image'],
      sizeType: ['compressed'],
      success: res => {
        const tempFiles = res.tempFiles.map(file => file.tempFilePath);
        this.setData({
          fileList: [...this.data.fileList, ...tempFiles]
        });
      }
    });
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    this.data.fileList.splice(index, 1);
    this.setData({ fileList: this.data.fileList });
  },

  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.fileList[index],
      urls: this.data.fileList
    });
  },
})